# -*- coding: utf-8 -*-
import json
from urllib import request as urlRequest


def getInterfaceList(request):
    request.cursor_standard.execute('''
        select * from  interface order by type,name
    ''')
    rows = request.cursor_standard.fetchall()
    return json.dumps(rows, ensure_ascii=False)

def updateInterface(request):
    request.cursor_standard.execute(request.formatSql('''
        update interface 
        set type = '${type}',
            name = '${name}',
            url='${url}',
            explain='${explain}' 
        where id = ${id}
    '''))
    return str(request.cursor_standard.rowcount)

def insertInterface(request):
    request.cursor_standard.execute(request.formatSql('''
        insert into interface(
            type,name,url,explain
        )values(
            '${type}','${name}','${url}','${explain}'
        )
    '''))
    return str(request.cursor_standard.rowcount)

def getLogList(request):
    request.cursor_standard.execute('''
        select 
            convert(varchar,log.invoke_time,25) invoke_time,
            log.invoke_state,
            log.msg,
            interface.name,
            interface.type
        from interface_invoke_log log
        inner join interface on log.id = interface.id
        order by invoke_time desc
    ''')
    rows = request.cursor_standard.fetchall()
    return json.dumps(rows, ensure_ascii=False)

#远程接口调用，需要发送http请求
def exeInterface(request):
    return_str = ""
    id_str = request.get("id")
    print("准备调用：",id_str)
    for one_id in id_str.split("^"):
        if one_id == "":
            continue
        request.set("one_id",one_id)

        request.cursor_standard.execute(request.formatSql('''
            select id,type,name,url 
            from  interface where id = ${one_id}
        '''))
        rows = request.cursor_standard.fetchall()
        id = rows[0]['id']
        type = rows[0]['type']
        name = rows[0]['name']
        url = rows[0]['url']
        print("准备发起请求：",url)
        response = urlRequest.urlopen(url, data=None, timeout=60*60*5)
        page = response.read().decode('utf-8')
        print("得到响应：",page)

        #回写标记
        request.cursor_standard.execute(request.formatSql('''
            insert into interface_invoke_log(id,invoke_state,msg,invoke_time) 
            values({},{},'{}',getdate()) 
        '''.format(id,200,page)))
        return_str = return_str + page
    return return_str


